<script setup>
import {defineEmits, defineProps, ref} from "vue";
import {useRouter} from "vue-router"
import request from '@/api/request'

let router = useRouter();

let emits = defineEmits(["ref-table"])
let props = defineProps(["data"])
let vendor = ref([])
let warehouse = ref([])
let productionPlan = ref([])
let purchaseOrder = ref({ ...props.data })
let purchaseDetails = ref([])

purchaseDetails.value = JSON.parse(JSON.stringify(purchaseOrder.value.purchaseDetailsList))
let purchaseDetails1 = ref([])
let User = ref([])

let onSubmit = () => {
    purchaseOrder.value.purchaseDetailsList = purchaseDetails.value
    console.log(purchaseOrder.value);

    request({
        url: "/purchaseOrder",
        method: "put",
        data: purchaseOrder.value
    }).then(res => {
        emits("ref-table")
    })
}

let location = () => {
    request({
        //查询供应商
        url: "/vendor",
        method: "get",
        data: {
            current: 1,
            size: 1000
        }

    }).then(res => {
        vendor.value = res.data.records;
    })

    request({
        //查询仓库
        url: "/warehouse",
        method: "get",
        params: {
            current: 1,
            size: 1000
        }
    }).then(res => {
        warehouse.value = res.data.date
    })
    request({
        //查询生产计划
        url: "/production/plan/page",
        method: "get",
        params: {
            current: 1,
            size: 1000
        }
    }).then(res => {
        productionPlan.value = res.data.records;
    })
    request({
        //查询员工
        url: "/system/user/list",
        method: "post",
        data: {
            current: 1,
            size: 1000
        }
    }).then(res => {
        User.value = res.data.records
    })
}
location()
let loadSize = 0;
//查询生产计划详情
let a = async () => {
    let responseData = null;
    await request({
        //查询生产计划
        url: "/production/plan/selectBom",
        method: "get",
        params: {
            planId: purchaseOrder.value.purchaseOrderProductionPlanningId
        }
    }).then(res => {
        responseData = res;
        
    })
    purchaseDetails1.value = responseData.data.productionPlanDetails;
        for (let i = 0; i < purchaseDetails1.value.length; i++) {
            for (let o = 0; o < purchaseDetails1.value[i].boss.length; o++) {
                purchaseDetails1.value[i].boss[o].purchaseDetailsQuantityPurchased = purchaseDetails1.value[i].boss[o].materialRatio * purchaseDetails1.value[i].planQuantity;
                purchaseDetails1.value[i].boss[o].purchaseDetailsProductsId = purchaseDetails1.value[i].boss[o].specificationsAndModels;
                purchaseDetails.value.push(purchaseDetails1.value[i].boss[o]);
            }
        }
        //去重
        let zong = [];
        for (let i = 0; i < purchaseDetails.value.length; i++) {
            let detail = { ...purchaseDetails.value[i] };
            for (let j = i + 1; j < purchaseDetails.value.length; j++) {
                let detailj = { ...purchaseDetails.value[j] };
                
            }
            let exist = zong.filter(o => {
                return detail.purchaseDetailsProductsId == o.purchaseDetailsProductsId
            })
            if (exist.length <= 0) {
                zong.push(detail)
            }
        }
        //原价
        purchaseOrder.value.purchaseOrderTotalQuantity = 0
        for (let i = 0; i < zong.length; i++) {
            const o = zong[i];
            await getPrice(o);
            purchaseOrder.value.purchaseOrderTotalQuantity += zong[i].purchaseDetailsQuantityPurchased;
        }
        purchaseDetails.value = zong;
}
a()

let getPrice = async (zong) => {
    await request({
        //查询供应商价格
        url: "/supplierPrices/getSupplierPrices",
        method: "get",
        params: {
            supplierpricesProductsid: zong.purchaseDetailsProductsId
        }
    }).then(res => {
        zong.supplierP = res.data
        loadSize++;
    })
    
}
// 计算金额
const calcPrice = () => {
    purchaseOrder.value.purchaseOrderPrice = 0
    for (let i = 0; i < purchaseDetails.value.length; i++) {
        let detail = purchaseDetails.value[i]
        if (detail.purchaseDetailsOriginalPrice) {
            purchaseOrder.value.purchaseOrderPrice += detail.purchaseDetailsOriginalPrice
        }
    }
   
    
    purchaseOrder.value.purchaseOrderPreferentialPrice = purchaseOrder.value.purchaseOrderPrice - purchaseOrder.value.purchaseOrderDiscountAmount
    purchaseOrder.value.purchaseOrderDiscountRate = (purchaseOrder.value.purchaseOrderPreferentialPrice / purchaseOrder.value.purchaseOrderPrice).toFixed(2)
    purchaseOrder.value.purchaseOrderTheAmountIsCapitalized = convertToRMB(purchaseOrder.value.purchaseOrderPreferentialPrice);
    purchaseOrder.value.purchaseOrderNoPreferentialPrice = (purchaseOrder.value.purchaseOrderPreferentialPrice * 0.98).toFixed(2)

}

function convertToRMB(amount){
    const digits =['零','壹','贰','叁','肆','伍','陆','柒','捌','玖'];
    const units =['','拾','佰','仟','万','拾万','佰万','仟万','亿','拾亿','佰亿']
    const [integerPart,decimalPart]= String(amount).split('.');
    const integerDigits = integerPart.split('').map(digit => digits[parseInt(digit)]);
    let result = '';
    for(let i=0;i<integerDigits.length;i++){
        result += integerDigits[i]+ units[integerDigits.length -1- i];
    }
    if(decimalPart){
        const decimalDigits = decimalPart.split('').map(digit =>digits[parseInt(digit)]);result +='点'+decimalDigits.join('');
        }
    return result;
}
// 供应商选择变化
let jisuan = async (val) => {
    await request({
        //查询生产计划
        url: "/supplierPrices",
        method: "get",
        params: {
            supplierPricesId: val
        }
    }).then(res => {
        let supplier = res.data.records[0]
        if (supplier) {
            let detail = purchaseDetails.value.filter(detail => detail.purchaseDetailsSupplierPricesId == supplier.supplierPricesid)[0]
            detail.purchaseDetailsOriginalPrice = detail.purchaseDetailsQuantityPurchased * supplier.supplierpricesStandardunitprice
            detail.purchaseDetailsActualPrice = detail.purchaseDetailsOriginalPrice
            detail.purchaseDetailsNoActualPrice = (detail.purchaseDetailsActualPrice * 0.98).toFixed(2)
            calcPrice();
        }
    })

}

</script>
<template>
    <div>
        <el-card>
            <template #header>
                <el-form :model="purchaseOrder" ref="form" :inline="false" class="card_wrap">
                    <el-form-item label="采购订单名称：" prop="purchaseOrderName" class="c_item">
                        <el-input v-model="purchaseOrder.purchaseOrderName" style="width: 150px;"></el-input>
                    </el-form-item>
                    <el-form-item label="生产计划订单" prop="purchaseOrderProductionPlanningId" class="c_item">
                        <el-select class="sousuo" v-model="purchaseOrder.purchaseOrderProductionPlanningId"
                            style="width:150px" @change="a">
                            <el-option v-for="item in productionPlan" :label="item.planName" :value="item.planId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="订单签订时间" prop="purchaseOrderDateOfSigning" class="c_item">
                        <el-date-picker v-model="purchaseOrder.purchaseOrderDateOfSigning" type="date"
                            value-format="YYYY-MM-DD" placeholder="选择日期时间">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="交货时间" prop="purchaseOrderDeliveryDate" class="c_item">
                        <el-date-picker v-model="purchaseOrder.purchaseOrderDeliveryDate" type="date"
                            value-format="YYYY-MM-DD" placeholder="选择日期时间">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="采购员工" prop="purchaseOrderEmployeeId" class="c_item">
                        <el-select class="sousuo" v-model="purchaseOrder.purchaseOrderEmployeeId" style="width: 150px;">
                            <el-option v-for="item in User" :label="item.nickname" :value="item.id + ''">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="供应商" prop="purchaseOrderVendorId" class="c_item">
                        <el-select class="sousuo" v-model="purchaseOrder.purchaseOrderVendorId" style="width: 150px;">
                            <el-option v-for="item in vendor" :label="item.vendorName" :value="item.vendorId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="预入库仓库" prop="purchaseOrderInboundWarehouse" class="c_item">
                        <el-select class="sousuo" v-model="purchaseOrder.purchaseOrderInboundWarehouse"
                            style="width: 150px;">
                            <el-option v-for="item in warehouse" :label="item.warehouseName" :value="item.warehouseId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="采购总数量：" prop="purchaseOrderTotalQuantity" class="c_item">
                        <el-input-number v-model="purchaseOrder.purchaseOrderTotalQuantity" disabled
                            style="width: 150px;"></el-input-number>
                    </el-form-item>
                    <el-form-item label="采购原价：" prop="purchaseOrderPrice" class="c_item">
                        <el-input-number v-model="purchaseOrder.purchaseOrderPrice" disabled
                            style="width: 150px;"></el-input-number>
                    </el-form-item>
                    <el-form-item label="优惠金额：" prop="purchaseOrderDiscountAmount" class="c_item">
                        <el-input-number v-model="purchaseOrder.purchaseOrderDiscountAmount" @change="calcPrice" @blur="calcPrice"
                            style="width: 150px;"></el-input-number>
                    </el-form-item>
                    <el-form-item label="折扣率：" prop="purchaseOrderDiscountRate" class="c_item">
                        <el-input v-model="purchaseOrder.purchaseOrderDiscountRate" disabled
                            style="width: 150px;"></el-input>%
                    </el-form-item>
                    <el-form-item label="优惠后采购金额：" prop="purchaseOrderPreferentialPrice" class="c_item">
                        <el-input-number v-model="purchaseOrder.purchaseOrderPreferentialPrice" disabled
                            style="width: 150px;"></el-input-number>
                    </el-form-item>
                    <el-form-item label="金额大写：" prop="purchaseOrderTheAmountIsCapitalized" class="c_item">
                        <el-input v-model="purchaseOrder.purchaseOrderTheAmountIsCapitalized" disabled
                            style="width: 200px;"></el-input>
                    </el-form-item>
                    <el-form-item label="优惠后采购金额（不含税）：" prop="purchaseOrderNoPreferentialPrice" class="c_item">
                        <el-input v-model="purchaseOrder.purchaseOrderNoPreferentialPrice" disabled
                            style="width: 150px;"></el-input>
                    </el-form-item>
                    <el-form-item label="审批人：" prop="purchaseOrderApprover" class="c_item">
                        <el-select v-model="purchaseOrder.purchaseOrderApprover" style="width: 150px;">
                            <el-option v-for="item in User" :label="item.nickname" :value="item.id+''">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="采购状态" prop="purchaseOrderState" class="c_item">
                        <el-select v-model="purchaseOrder.purchaseOrderState" style="width: 150px;">
                            <el-option :value="'申请中'" label="申请中"/>
                            <el-option :value="'正在采购'" label="正在采购"/>
                            <el-option :value="'采购完成'" label="采购完成"/>
                        </el-select>
                    </el-form-item>

                </el-form>

                <el-table v-if="purchaseDetails.length == loadSize" :data="purchaseDetails" border>
                    <el-table-column prop="purchaseDetailsProductsId" label="产品编码" width="100px;" />
                    <el-table-column prop="purchaseDetailsSupplierPricesId" label="供应商价格" width="180px;">
                        <template #default="{ row }">
                            <el-select v-model="row.purchaseDetailsSupplierPricesId" style="width: 150px;"
                                @change="jisuan">
                                <el-option v-for="item in row.supplierP" :label="item.supplierpricesStandardunitprice"
                                    :value="item.supplierPricesid">
                                </el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="purchaseDetailsQuantityPurchased" label="采购数量" width="120px;" />
                    <el-table-column prop="purchaseDetailsOriginalPrice" label="采购原价合价" width="180px;">
                        <template #default="scope">
                            <el-input v-model="scope.row.purchaseDetailsOriginalPrice" disabled></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="purchaseDetailsActualPrice" label="采购实际合价" width="180px;">
                        <template #default="scope">
                            <el-input v-model="scope.row.purchaseDetailsActualPrice" disabled></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="purchaseDetailsNoActualPrice" label="实际采购价（不含税）" width="190px;">
                        <template #default="scope">
                            <el-input v-model="scope.row.purchaseDetailsNoActualPrice" disabled></el-input>
                        </template>
                    </el-table-column>
                </el-table>

                <el-form-item>
                    <el-button type="primary" @click="onSubmit">保存</el-button>
                </el-form-item>
            </template>
        </el-card>
    </div>
</template>
<style scoped>
.card_wrap {
    width: 98%;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
}

.c_item {
    flex: 1;
    margin: 0 5px 15px 0;
    width: 50%;
    min-width: calc((100% - 10px)/2);
    max-width: calc((100% - 10px)/2);
}
</style>